#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <cstdio>

int sum=1000;
void* fight(void* arg)
{
    while(1)
    {
        pthread_mutex_lock((pthread_mutex_t*)arg);
        if(sum>0)
        {
        usleep(1000);
        sum--;
        int num=pthread_self();
        std::cout<<"ticket remain "<<sum <<" "<<num<<std::endl;
        }
        pthread_mutex_unlock((pthread_mutex_t*)arg);
    }
    return nullptr;
}
int main()
{
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex,nullptr);

    int cnt=1;
    pthread_t p1;
    pthread_t p2;
    pthread_t p3;
    pthread_t p4;
    pthread_create(&p1,nullptr,fight,&mutex);
    pthread_create(&p2,nullptr,fight,&mutex);
    pthread_create(&p3,nullptr,fight,&mutex);
    pthread_create(&p4,nullptr,fight,&mutex);
    pthread_join(p1,nullptr);
    pthread_join(p2,nullptr);
    pthread_join(p3,nullptr);
    pthread_join(p4,nullptr);
    pthread_mutex_destroy(&mutex);
    return 0;
}
